//
//  JWPickerViewController.swift
//  oa
//
//  Created by lin on 2022/3/9.
//

import UIKit
#if canImport(XBPickerView)
import XBPickerView
#endif
#if canImport(XBDialog)
import XBDialog
#endif


/// 协议
public typealias JWPickerViewProtocol = JWPickerViewControllerDataSource & JWPickerViewControllerDelegate


public class JWPickerViewController: UIViewController {
    
    /// 组合协议
    private let combinationProtocol: JWPickerViewProtocol
    
    /// 点击背景是否隐藏
    @objc public var backgoundTapDismissEnable = true
    
    /// 点击背景取消事件
    @objc public var backgoundTapCancelHandler: (() -> Void)?
    
    /// 头部View
    private lazy var headerView: JWPickerMenuHeaderView = {
        let temHeaderView = JWPickerMenuHeaderView()
        temHeaderView.backgroundColor = UIColor.white
        return temHeaderView
    }()
    
    /// 选择器
    private lazy var datePicker: PickerView = {
        let temDatePicker = PickerView()
        temDatePicker.backgroundColor = UIColor.white
        return temDatePicker
    }()
    
    /// 底部安全区域
    private lazy var safeAreaView: UIView = {
        let it = UIView()
        it.backgroundColor = UIColor.white
        return it
    }()
    
    /// 默认高度
    private lazy var rowHeight: CGFloat = 50
    
    /// 菜单高度
    private lazy var headerViewHeight: CGFloat = self.rowHeight
    
    /// 选择日期高度
    private lazy var pickerHeight: CGFloat = self.rowHeight * 5
    
    /// 转场动画
    private var presentAnimator: XBPresentAnimator!
    
    /// 配置
    private var styleConfig: JWTextPickerViewConfig
    
    
    
    /// 初始化
    public init(combinationProtocol: JWPickerViewProtocol,
                styleConfig: JWTextPickerViewConfig = JWTextPickerViewConfig.defaultConfig()) {
        
        
        self.combinationProtocol = combinationProtocol
        
        self.styleConfig = styleConfig
        
        super.init(nibName: nil, bundle: nil)
        
        setupData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        configData()
        
        configDataSource()
        
        updateStyle(styleConfig)
    }
    
    open override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        /// 设置上方圆角
        let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: styleConfig.headViewCornerRadius, height: styleConfig.headViewCornerRadius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        view.layer.mask = mask
    }
    
    /// 配置默认选择
    private func configDataSource() {
        combinationProtocol.pickerDefaultSelected(self)
    }
    
    func updateStyle(_ styleConfig: JWTextPickerViewConfig) {
        
        headerView.cancelNormalColor = styleConfig.cancelTextColor
        headerView.confirmNormalColor = styleConfig.submitTextColor

        headerView.cancelHighlightedColor = styleConfig.cancelTextHighLightColor ?? headerView.cancelNormalColor
        headerView.confirmHighlightedColor = styleConfig.submitTextHighLightColor ?? headerView.confirmNormalColor

        headerView.cancelButton.titleLabel?.font = styleConfig.cancelTextFont
        headerView.confirmButton.titleLabel?.font = styleConfig.submitTextFont
        
        headerView.lineColor = styleConfig.headViewSeparatorColor

        headerView.titleLabel.font = styleConfig.titleTextFont
        headerView.titleLabel.textColor = styleConfig.titleTextColor
        
        datePicker.lineColor = styleConfig.contentSeparatorColor
        datePicker.selectedAttributes = [.foregroundColor: styleConfig.contentTextSelectedColor, .font: styleConfig.contentSelectedFont]

    }
    
}


extension JWPickerViewController {
    
    func setupData() {
        
        let temHeight = self.pickerHeight + self.headerViewHeight
        self.presentAnimator = XBPresentAnimator(self)
        self.presentAnimator.menu { (config) in
            config.presentingScale = 1.0
            if #available(iOS 11.0, *) {
                let areaInsetsBottom = UIApplication.shared.keyWindow?.rootViewController?.view.safeAreaInsets.bottom ?? 0.0
                config.menuType = .bottomHeight(h: CGFloat(temHeight + areaInsetsBottom))
            } else {
                config.menuType = .bottomHeight(h: temHeight)
            }
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizer))
            tap.numberOfTapsRequired = 1
            config.gestureRecognizer = tap
        }
        
    }
    
    func setupUI() {
        
        datePicker.delegate = self
        datePicker.dataSource = self
        
        view.addSubview(safeAreaView)
        view.addSubview(headerView)
        view.addSubview(datePicker)
        
        /// 布局datePicker
        datePicker.translatesAutoresizingMaskIntoConstraints = false
        datePicker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        datePicker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        datePicker.heightAnchor.constraint(equalToConstant: pickerHeight).isActive = true
        if #available(iOS 11.0, *) {
            datePicker.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        } else {
            datePicker.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        }
        
        safeAreaView.translatesAutoresizingMaskIntoConstraints = false
        safeAreaView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        safeAreaView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        safeAreaView.topAnchor.constraint(equalTo: datePicker.bottomAnchor).isActive = true
        safeAreaView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        
        /// 布局headerView
        headerView.translatesAutoresizingMaskIntoConstraints = false
        headerView.leftAnchor.constraint(equalTo: datePicker.leftAnchor).isActive = true
        headerView.rightAnchor.constraint(equalTo: datePicker.rightAnchor).isActive = true
        headerView.heightAnchor.constraint(equalToConstant: rowHeight).isActive = true
        headerView.bottomAnchor.constraint(equalTo: datePicker.topAnchor).isActive = true
        
        
        headerView.cancelHandler = { [weak self] () -> Void in
            guard let self = self else { return }
            self.combinationProtocol.pickerCancel(self)
        }
        headerView.confirmHandler = { [weak self] () -> Void in
            guard let self = self else { return }
            self.combinationProtocol.pickerConfirm(self)
        }
        
    }
    
    func configData() {
        self.headerView.titleLabel.attributedText = self.combinationProtocol.title
    }
    
    /// 手势点击
    @objc func tapGestureRecognizer() {
        
        if backgoundTapDismissEnable {
            self.combinationProtocol.pickerCancel(self)
            self.dismiss(animated: true, completion: nil)
        }
    }
    
}

extension JWPickerViewController: UIPickerViewDataSource {
    
    public func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return combinationProtocol.numberOfComponents(in: self)
    }
    
    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return combinationProtocol.pickerContentView(self, numberOfRowsInComponent: component)
    }
    
}

extension JWPickerViewController: UIPickerViewDelegate {
    public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return combinationProtocol.pickerContentView(self, widthForComponent: component)
    }
    
    public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return combinationProtocol.pickerContentView(self, rowHeightForComponent: component)
    }
    
    public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let cell = PickerCommonView()
        cell.labelTitle.text = combinationProtocol.pickerContentView(self, titleForRow: row, forComponent: component)
        return cell
    }
    
    public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        combinationProtocol.pickerContentView(self, didSelectRow: row, inComponent: component)
    }
}

// MARK: - public
extension JWPickerViewController {
    
    /// 点击
    public func selectRow(_ row: Int, inComponent component: Int, animated: Bool) {
        datePicker.selectRow(row, inComponent: component, animated: false)
    }
    
    
    /// 刷新Component
    public func reloadComponent(_ component: Int) {
        datePicker.reloadComponent(component)
    }
}
